import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
import logger from 'morgan'
import session from 'express-session'
import models from './models'
import middleware from './middleware'
import api from './api'
import config from './config'
let app = express()
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function (socket) {
  console.log('a user connected');
  socket.on('disconnect', function () {
    console.log('user disconnected');
  });
  socket.on('message', function (msg) {
    console.log(msg);
    io.emit('message', msg);
  });
});

  // connect to db
models.sequelize.sync().then(() => {
  app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  })

  app.use(bodyParser.json())

  // set logging
  app.use(logger('dev'))

  // internal middleware
  app.set('trust proxy', 1) // trust first proxy
  app.use(session({
    secret: 'order-manager-system',
    resave: true
  }))
  app.use(middleware({ config }))
  app.use('/api', api({ config }))
  app.use('/static', express.static('./src/static'));
  http.listen(process.env.PORT || config.port)

  console.log(`Started on port ${http.address().port}`)
}).catch(e => console.error(e))

export default app
